<?php

namespace App\Services\RefreshGoldProductTakeState;

use App\Models\GoldProduct;
use Illuminate\Support\Collection;
use Rainsens\Dinglog\Facades\Dinglog;

class RefreshGoldProductTakeState
{
	public function __invoke()
	{
		Dinglog::text("========== Start refreshing gold products taken states......");
		
		GoldProduct::query()
			->whereNull('finished_at')
			->chunks(20, function (Collection $products) {
				
				if ($products->isEmpty()) return false;
				
				/**
				 * @var GoldProduct $product
				 */
				foreach ($products as $product) {
					
					if ($product->is_taken_today
						and $product->last_taken_at->isToday()) {
						continue;
					}
					
					$product->update([
						'is_taken_today' => false,
						'last_taken_at' => null
					]);
					
					usleep(1000);
				}
				
				return true;
				
			});
		
		Dinglog::text("========== Gold products taken states refreshed......");
	}
}
